<template>
  <t-dialog v-model:visible="drawerVisible" header="选择封面" size="large" @confirm="form.submit()">
    <template #body>
      <t-form ref="form" :data="projectDetail" :rules="rules" @submit="onSubmit">
        <t-form-item label="封面ID" name="fileId">
          <t-input-number v-model="projectDetail.fileId" theme="normal" />
        </t-form-item>
      </t-form>
    </template>
  </t-dialog>
</template>

<script setup lang="tsx">
import { FormRules, MessagePlugin, SubmitContext } from 'tdesign-vue-next';
import { ref, watch } from 'vue';

import { saveOrUpdate } from '@/api/common';

const drawerVisible = ref(false);
const projectDetail: any = ref({});
const form = ref();

const emit = defineEmits(['update:visible', 'refreshTable']);

const props = defineProps<{
  visible: boolean;
  data: {};
}>();

const rules: FormRules = {
  fileId: [{ required: true, message: '请输入', type: 'error' }],
};

const onSubmit = async ({ validateResult, firstError }: SubmitContext) => {
  if (!firstError) {
    await saveOrUpdate('/project/selectCoverImage', {
      projectId: projectDetail.value.projectId,
      fileId: projectDetail.value.fileId,
    });
    MessagePlugin.success('提交成功');
    drawerVisible.value = false;
    // await emit.refreshTable();
    await emit('refreshTable');
  } else {
    console.log('Errors: ', validateResult);
    MessagePlugin.warning(firstError);
  }
};

watch(
  () => drawerVisible.value,
  (val) => {
    emit('update:visible', val);
  },
);

watch(
  () => props.visible,
  (val) => {
    drawerVisible.value = val;
  },
);

watch(
  () => props.data,
  async (val) => {
    projectDetail.value = val;
  },
);
</script>
